package org.itt.cp.signeddoc;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.TreeMap;

import org.apache.log4j.Logger;
import org.itt.FooUtil;
import org.itt.Properties;
import org.itt.ap.Reader;
import org.itt.ap.Source;

public class SignedDocReader implements Reader {
	private static Logger logger = Logger.getLogger("SigendDocReader");

	public static void printProgBar(long l) {
		StringBuilder bar = new StringBuilder("[");

		for (int i = 0; i < 50; i++) {
			if (i < (l / 2)) {
				bar.append("=");
			} else if (i == (l / 2)) {
				bar.append(">");
			} else {
				bar.append(" ");
			}
		}

		bar.append("]   " + l + "%     ");
		System.out.print("\r" + bar.toString());
	}

	@Override
	public void parse(Source source) {
		int counter = 0;
		String line;
		BufferedReader br = null;
		SignedDoc request = null;
		//long progress = 0;

		try {
			TreeMap<Integer, Source> map = new TreeMap<Integer, Source>();
			logger.debug("Istanzio una hashmap di oggetti SignedDoc");

			long fileSize = new File(Properties.get().WORKDIR + File.separator
					+ Properties.get().SOURCE).length();
			logger.debug("File sorgente: " + Properties.get().WORKDIR
					+ File.separator + Properties.get().SOURCE
					+ " - dimensione: " + fileSize + " bytes");

			br = new BufferedReader(new FileReader(Properties.get().WORKDIR
					+ File.separator + Properties.get().SOURCE));
			logger.info("Mi preparo a leggere il file sorgente: "
					+ Properties.get().WORKDIR + File.separator
					+ Properties.get().SOURCE);

			long start = System.nanoTime();

			while ((line = br.readLine()) != null) {
				/*
				 * progress += line.length();
				 * printProgBar(progress * 100 / fileSize);
				 * 
				 */

				line = line.trim();

				if (!line.contains("##")) {
					SignedDoc signedDoc = (SignedDoc) map.get(counter - 1);
					signedDoc.setSignedDoc(signedDoc.getSignedDoc() + line);
				} else {
					logger.debug("Nuova richiesta:");
					
					request = new SignedDoc();

					String[] requestArray = line
							.split(Properties.get().SPLIT_BY);

					/* ID */
					request.setId(Integer.valueOf(requestArray[0]));
					logger.debug("ID: " + request.getId());
					
					/* CALLER */
					request.setCallerId(requestArray[1]);
					logger.debug("CALLER: " + request.getCallerId());
					
					/* CALLER_NAME */
					request.setCallerName(requestArray[2]);
					logger.debug("CALLER_NAME: " + request.getCallerName());
					
					/* CALLER_SURNAME */
					request.setCallerSurname(requestArray[3]);
					logger.debug("CALLER_SURNAME: " + request.getCallerSurname());
							
					/* CALLER_COUNTRY */
					request.setCallerCountry(requestArray[4]);
					logger.debug("CALLER_COUNTRY: " + request.getCallerCountry());
					
					/* CALLER_FISCALCODE */
					request.setCallerFiscalcode(requestArray[5]);
					logger.debug("CALLER_FISCALCODE: " + request.getCallerFiscalcode());
					
					/* USER */
					request.setUserId(requestArray[6]);
					logger.debug("USER: " + request.getUserId());
					
					/* USER_NAME */
					request.setUserName(requestArray[7]);
					logger.debug("USER_NAME: " + request.getUserName());
					
					/* USER_SURNAME */
					request.setUserSurname(requestArray[8]);
					logger.debug("USER_SURNAME: " + request.getUserSurname());
							
					/* USER_COUNTRY */
					request.setUserCountry(requestArray[9]);
					logger.debug("USER_COUNTRY: " + request.getUserCountry());
							
					/* USER_FISCALCODE */
					request.setUserFiscalcode(requestArray[10]);
					logger.debug("USER_FISCALCODE: " + request.getUserFiscalcode());
							
					/* STATUS */
					request.setRequestStatus(requestArray[11]);
					logger.debug("STATUS: " + request.getRequestStatus());
							
					/* PROFILE */
					request.setProfile(requestArray[12]);
					logger.debug("PROFILE: " + request.getProfile());
					
					/* SUPPORT */
					request.setSupport(requestArray[13]);
					logger.debug("SUPPORT: " + request.getSupport());
							
					/* INSERT_DATE */
					request.setCreationTime(new SimpleDateFormat(
							"dd/mm/yyyy hh:mm:ss").parse(requestArray[14]));
					logger.debug("INSERT_DATE: " + request.getCreationTime());

					/* MODIFY_DATE */
					request.setUpdateTime(new SimpleDateFormat(
							"dd/mm/yyyy hh:mm:ss").parse(requestArray[15]));
					logger.debug("MODIFY_DATE: " + request.getUpdateTime());
					
					/* SIGNED_DOC */
					request.setSignedDoc(requestArray[16]);
					logger.trace("SIGNED_DOC: " + request.getSignedDoc());
					
					map.put(counter, request);

					counter++;
				}
			}

			/* 
			 * printProgBar(100);
			 * System.out.print("\n");
			 * 
			 */

			logger.info("Ho letto " + counter + " righe");
			logger.info("Durata lettura: "
					+ FooUtil.prettyPrintTime(System.nanoTime() - start));

			source.setMap(map);
			logger.debug("Finalizzo la hashmap di oggetti SignedDoc");
		} catch (NumberFormatException | IOException | ParseException e) {
			logger.error(e);
            System.exit(1);
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					logger.error(e);
				}
			}
		}
	}
}
